package com.hsck.order.kds.base.isnoam.network

import com.google.gson.GsonBuilder
import com.hsck.order.kds.base.Constants
import com.hsck.order.kds.base.isnoam.log.XLog
import com.jakewharton.retrofit2.adapter.kotlin.coroutines.CoroutineCallAdapterFactory
import okhttp3.*
import okhttp3.ResponseBody.Companion.toResponseBody
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.converter.scalars.ScalarsConverterFactory
import java.io.IOException
import java.util.*
import java.util.concurrent.TimeUnit
import javax.net.ssl.*


object RetrofitManager {

    private val mOkClient = OkHttpClient.Builder().callTimeout(20, TimeUnit.SECONDS)
        .connectTimeout(20, TimeUnit.SECONDS).readTimeout(20, TimeUnit.SECONDS)
        .writeTimeout(20, TimeUnit.SECONDS).retryOnConnectionFailure(true).followRedirects(false)
        .addInterceptor(HttpHeadInterceptor()).addInterceptor(initCommonInterceptor())
        .addInterceptor(LoggingInterceptor())

    private var mRetrofit: Retrofit? = null


    fun initRetrofit(): RetrofitManager {
        mRetrofit = Retrofit.Builder().baseUrl(Constants.HTTP_URL).client(mOkClient.build())
            .addConverterFactory(ScalarsConverterFactory.create())
            .addCallAdapterFactory(CoroutineCallAdapterFactory()).addConverterFactory(
                GsonConverterFactory.create(
                    GsonBuilder().registerTypeAdapterFactory(GsonTypeAdapterFactory()).create()
                )
            )

            .build()
        return this
    }

    fun <T> getService(serviceClass: Class<T>): T {
        if (mRetrofit == null) {
            throw UninitializedPropertyAccessException("Retrofit必须初始化")
        } else {
            return mRetrofit!!.create(serviceClass)
        }
    }

    private class LoggingInterceptor : Interceptor {
        @Throws(IOException::class)
        override fun intercept(chain: Interceptor.Chain): Response {
            val request = chain.request()
            val response = chain.proceed(chain.request())
            val responseBody = response.body ?: return response
            val mediaType = responseBody.contentType()
            val content = response.body!!.string()

            // 获取请求参数
            val method = request.method
            val httpUrl = request.url
            val path = httpUrl.encodedPath
            val query = httpUrl.encodedQuery
            XLog.i("请求对象： $request \n请求Method: ${request.method} \n" + "请求RUL: $path \n请求Query: $query")
            XLog.i(content)
            return response.newBuilder().body(content.toResponseBody(mediaType)).build()
        }
    }

    private class HttpHeadInterceptor : Interceptor {
        @Throws(IOException::class)
        override fun intercept(chain: Interceptor.Chain): Response {
            val request = chain.request()
            val builder = request.newBuilder()
//            val loginData = MMKVUtils.getParcelable<LoginData>(Constants.LOGIN_INFO)
//            loginData?.access_token?.let {
//                builder.addHeader("Authorization", "Bearer $it")
//            }
//            builder.addHeader("clientid", Constants.CLIENT_ID)
            return chain.proceed(builder.build())
        }
    }

    private fun initCommonInterceptor(): Interceptor {
        return Interceptor { chain ->
            val request = chain.request().newBuilder()
                .addHeader("Content-Type", "BaseApplicationlication/json")
                .addHeader("charset", "UTF-8").build()
            chain.proceed(request)
        }
    }
}